package fr.appliClient.server.restservice;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import fr.appliClient.server.dto.VehicleDTO;
import fr.appliClient.server.entity.Vehicle;
import fr.appliClient.server.mapping.VehicleMapping;
import fr.appliClient.server.service.VehicleService;

@Controller
@RequestMapping("/vehicle")
@Transactional
public class VehicleRestService {

	@Autowired
	private VehicleMapping vehicleMapping;

	@Autowired
	private VehicleService vehicleService;

	/**
	 * Rest service for creating a vehicle
	 * 
	 * @param vehicleDTO
	 * @return
	 */
	@RequestMapping(value = "/create/{v}", method = RequestMethod.GET)
	public VehicleDTO createVehicle(@PathVariable("v") VehicleDTO vehicleDTO) {

		Vehicle vehicle = this.vehicleMapping.vehicleDTOToVehicle(vehicleDTO);
		try {
			vehicle = this.vehicleService.createVehicle(vehicle);

			return this.vehicleMapping.vehicleToVehicleDTO(vehicle);
		} catch (Exception e) {
			return null;
		}
	}

	@RequestMapping(value = "/getAll", method = RequestMethod.GET)
	public @ResponseBody
	List<VehicleDTO> getAllVehicles() {

		List<Vehicle> vehicles = this.vehicleService.getVehicles();
		List<VehicleDTO> dtos = new ArrayList<VehicleDTO>();

		for (Vehicle v : vehicles) {
			VehicleDTO dto = new VehicleDTO();
			dto.setRegistration("tset");
			dtos.add(dto);
			dtos.add(this.vehicleMapping.vehicleToVehicleDTO(v));
		}

		return dtos;
	}

	@RequestMapping(value = "/test", method = RequestMethod.GET)
	public @ResponseBody
	String test(ModelMap model) {

		model.addAttribute("test", "toto");
		return "toto";
	}
}
